<?php
/**
 * Created by PhpStorm.
 * User: zyark
 * Date: 2018/4/10
 * Time: 10:23
 */

namespace app\admin\logic;


use app\common\utils\Constant;
use app\common\utils\IDCardUtils;
use Exception;
use PHPExcel_Cell;
use PHPExcel_IOFactory;
use think\Db;

class OwnerLogic
{
    /**
     * 批量导入
     * @param $filename string 文件名
     * @param $village_id int 小区id
     * @param $admin_id int 管理员id
     * @param string $encode
     * @return array
     */
    public function import($filename,$village_id,$admin_id, $encode = 'utf-8')
    {
        if(empty($village_id)){
            return array('status'=>2,'msg'=>'请选择小区');
        }
        $count = model('Village')->where(array('id'=>$village_id))->count();
        if($count == 0){
            return array('status'=>2,'msg'=>'小区不存在');
        }
        if(empty($filename)){
            return array('status'=>2,'msg'=>'请上传Excel文件');
        }
        ini_set("memory_limit", "255M");
        Db::startTrans();
        $housePropertyIds = [];
        try {
            setlocale(LC_ALL, 'zh_CN');
            $objReader = PHPExcel_IOFactory::createReader('Excel5');//读取xls
            if (!$objReader->canRead($filename)) {
                //读取xlsx
                $objReader = PHPExcel_IOFactory::createReader('Excel2007');
                if (!$objReader->canRead($filename)) {
                    return array('status'=>2,'msg'=>'无法读取文件');
                }
            }
            $objPHPExcel = $objReader->load($filename);
            $objWorksheet = $objPHPExcel->getActiveSheet();
            $highestRow = $objWorksheet->getHighestRow();
            $highestColumn = $objWorksheet->getHighestColumn();
            $highestColumnIndex = PHPExcel_Cell::columnIndexFromString($highestColumn);
            $excelData = [];
            for ($row = 2; $row <= $highestRow; $row++) {
//                $value = (string)$objWorksheet->getCellByColumnAndRow(0, $row)->getValue();
//                if ($value == '') {
//                    continue;
//                }
                $excelData[$row] = [];
                for ($col = 0; $col < $highestColumnIndex; $col++) {
                    $value = (string)$objWorksheet->getCellByColumnAndRow($col, $row)->getValue();
                    if (!is_numeric($value) && $value != '') {
                        $value = mb_convert_encoding($value, 'utf-8');
                    }
                    $excelData[$row][] = $value;
                }
                $result = $this->checkData($excelData[$row],$row);
                if($result['status'] == 0){
                    Db::rollback();
                    $this->addImportLog($result['msg'],Constant::IMPORT_STATUS_FAILURE,$admin_id,$village_id);
                    return $result;
                }
                if ($row % 1000 == 0) {
                    $result = $this->executeImport($excelData,$village_id,$admin_id);
                    if($result['status'] == 0){
                        return $result;
                    }
                    $housePropertyIds = array_merge($housePropertyIds,$result['data']);
                }
            }
            if(count($excelData) > 0){
                $result = $this->executeImport($excelData,$village_id,$admin_id);
                if($result['status'] == 0){
                    return $result;
                }
                $housePropertyIds = array_merge($housePropertyIds,$result['data']);
            }
            if(count($housePropertyIds) > 0) {
                MessageLogic::getInstance()->sendMessageByHousePropertyPay($housePropertyIds);
            }
            //导入成功
            $remark = '导入成功';
            $status = Constant::IMPORT_STATUS_SUCCESS;
            $this->addImportLog($remark,$status,$admin_id,$village_id);//添加导入记录
            Db::commit();
            return array('status'=>1);
        }catch (Exception $e){
            Db::rollback();
            $remark = '服务器错误，'.$e->getMessage();
            $status = Constant::IMPORT_STATUS_FAILURE;
            $this->addImportLog($remark,$status,$admin_id,$village_id);//添加导入记录
            return array('status'=>0,'msg'=>'服务器错误，'.$e->getMessage());
        }
    }

    /**
     * 执行导入
     * @param $excelData
     * @param $village_id
     * @param $admin_id
     * @return array
     */
    private function executeImport(&$excelData,$village_id,$admin_id){
        $result = $this->importData($excelData, $village_id);
        $excelData = null;
        $excelData = [];
        if($result['status'] == 0){
            Db::rollback();
            $this->addImportLog($result['msg'],Constant::IMPORT_STATUS_FAILURE,$admin_id,$village_id);
        }
        return $result;
    }

    /**
     * 添加导入记录
     * @param $remark string 备注
     * @param $status int 成功或失败
     * @param $admin_id int 管理员id
     * @param $village_id int
     */
    private function addImportLog($remark,$status,$admin_id,$village_id){
        $log['create_time'] = time();
        $log['remark'] = $remark;
        $log['type'] = Constant::IMPORT_TYPE_HOUSE_PROPERTY;
        $log['status'] = $status;
        $log['admin_id'] = $admin_id;
        $log['village_id'] = $village_id;
        model('ImportLog')->insert($log);
    }

    /**
     * 导入数据
     * @param $excelData
     * @param $village_id
     * @return array
     */
    private function importData($excelData,$village_id){
        $current_row = 0;
        $ids = [];
        try {
            foreach ($excelData as $key => $row) {
                $current_row = $key;
                $owner['name'] = $row[0];//业主名
                $owner['id_card'] = $row[1];//身份证
                $owner['phone'] = $row[2];//手机号
                $owner_obj = model('Owner')->where(array('id_card' => $owner['id_card']))->find();
                if (!$owner_obj) {
                    $owner_obj = model('Owner')->create($owner);
                }
                if (!empty($owner_obj['user_id'])) {
                    $house['user_id'] = $owner_obj['user_id'];
                }
                $detail = $row[6];
                $map['detail'] = $detail;
                $map['village_id'] = $village_id;
                $count = model('HouseProperty')->where($map)->count();
                if ($count > 0) {
                    return array('status'=>0,'msg'=>"导入第{$current_row}行数据失败，该房产信息已经导入过",'data'=>[]);
                }
                $house['owner_id'] = $owner_obj['id'];
                $house['village_id'] = $village_id;
                $house['create_time'] = time();
                $house['building_number'] = $row[3];
                $house['floor_number'] = $row[4];
                $house['room_number'] = $row[5];
                $house['detail'] = $row[6];
                $house['water_charge'] = $row[7];
                $house['property_charge'] = $row[8];
                $house['charge_total'] = $row[7] + $row[8];
                $obj = model('HouseProperty')->create($house);
                $ids[] =$obj['id'];
            }
            return array('status'=>1,'data'=>$ids);
        }catch (Exception $e){
            return array('status'=>0,'msg'=>"导入第{$current_row}行数据失败，请检查数据格式是否正确 ".$e->getMessage(),'data'=>[]);
        }
    }

    private function checkData($row_value,$current_row){
        $msg = '';
        $result = array('status'=>1,'msg'=>'');
        if(count($row_value) != 9){
            $result['status'] = 0;
            $result['msg'] = "导入第{$current_row}行数据失败，该行数据不完整";
            return $result;
        }
        $this->checkNull($row_value,$msg,$result);
        if($result['status'] == 0){
            $result['msg'] = "导入第{$current_row}行数据失败，".$msg;
            return $result;
        }
        if(!is_numeric($row_value['4'])){//楼层号
            $result['status'] = 0;
            $msg.= ' 楼层号必须为数字';
        }
        if(!is_numeric($row_value['7'])){//未缴水费
            $result['status'] = 0;
            $msg.= ' 未缴水费必须为数字';
        }
        if(!is_numeric($row_value['8'])){//未缴物业费
            $result['status'] = 0;
            $msg.= ' 未缴物业费必须为数字';
        }
        $utils = new IDCardUtils();
        if(!$utils->validation_filter_id_card($row_value[1])){
            $result['status'] = 0;
            $msg.= ' 身份证格式不正确'.$row_value[1];
        }
        if(!is_mobile($row_value[2])){
            $result['status'] = 0;
            $msg.= ' 手机格式不正确';
        }
        if($result['status'] == 0){
            $result['msg'] = "导入第{$current_row}行数据失败，".$msg;
        }
        return $result;
    }

    private function checkNull($row_value,&$msg,&$result){
        if($row_value[0] == ''){
            $result['status'] = 0;
            $msg.= ' 业主名不能为空';
        }
        if($row_value[1] == ''){//身份证
            $result['status'] = 0;
            $msg.= ' 身份证不能为空';
        }
        if($row_value[2] == ''){//手机号
            $result['status'] = 0;
            $msg.= ' 手机号不能为空';
        }
        if($row_value[3] == ''){//大楼编号
            $result['status'] = 0;
            $msg.= ' 大楼编号不能为空';
        }
        if($row_value[4] == ''){//楼层号
            $result['status'] = 0;
            $msg.= ' 楼层号不能为空';
        }
        if($row_value[5] == ''){//房间号
            $result['status'] = 0;
            $msg.= ' 房间号不能为空';
        }
        if($row_value[6] == ''){//详细地址
            $result['status'] = 0;
            $msg.= ' 详细地址不能为空';
        }
        if($row_value[7] == ''){//未缴水费
            $result['status'] = 0;
            $msg.= ' 未缴水费不能为空';
        }
        if($row_value[8] == ''){//未缴物业费
            $result['status'] = 0;
            $msg.= ' 未缴物业费不能为空';
        }
    }

}